package cn.sangyy.gift.utils;

import cn.sangyy.gift.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author SangYY
 * @date: 2023/05/23/20:24
 */
@Component
public class SendEmail {
    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String username;


    public void sendSimple(String title,String content,String acceptMail){
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        //设置发送人
        mailMessage.setFrom(username);
        //邮件主题
        mailMessage.setSubject(title);
        //邮件内容
        mailMessage.setText(content);
        //收件人
        mailMessage.setTo(acceptMail);

        javaMailSender.send(mailMessage);
    }

    public void sendMime(String title,String content,String acceptMail,String imageUrl) {
        //创建复杂邮件对象
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        //发送复杂邮件的工具类
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,true,"utf-8");
            helper.setFrom(username);
            helper.setSubject(title);
            helper.setText("<h1>"+title+"</h1>"+content,true);
            //添加附件
//        helper.addAttachment("罗宾.jpg",new File("C:\\Users\\hm\\Desktop\\work\\aa.jpg"));
//        helper.addAttachment("压缩文件", new File("C:\\Users\\hm\\Desktop\\20191010\\2020-02-05-智能商贸-DAY4\\resources\\resources.zip"));
            //收件人
            helper.setTo(acceptMail);
            javaMailSender.send(mimeMessage);
        } catch (MessagingException e) {
            throw new BusinessException("邮件发送失败！"+e.getMessage());
        }
    }

}
